const $ = require("jquery");
const { shell, ipcRenderer } = require("electron");
const path = require("path");
const fs = require("fs");
const request = require("request");
const localFunc = require(path.join(__dirname,"../core/function"));
let isMousePress = false;
let isMovingWindow = false;
let mouseX, mouseY;
let projects = [];
let config = {};
let userDataPath = require("electron").remote.app.getPath("userData");
let refresh_interval = 5; //second
// main function
function autoUpdate() {
    update();
    setInterval(update, refresh_interval * 1000);
}

init();
setTimeout(autoUpdate, 1000);
////////////////////////////////////////////////////
//this is function
// constrct div about one project
function constrctProjectDiv(id, name) {
    var html = "<div id='" + id + "' class='list-item'><a>" + name + "</a></div>";
    return html;
}

//construct request url 
function construcUrl(name, token, url) {
    var resUrl = url;
    var pos = resUrl.indexOf("://");
    if (pos != -1) {
        resUrl = resUrl.slice(0, pos + 3) + name + ':' + token + '@' + resUrl.slice(pos + 3);
    }
    if (resUrl.charAt(resUrl.length - 1) == '/') {
        resUrl = resUrl.slice(0, resUrl.length - 1);
    }
    return resUrl;
}

// init
function init() {
    if(!fs.existsSync(path.join(userDataPath, "data/projects.json"))) {
        fs.writeFileSync(path.join(userDataPath, "data/projects.json"),"[]");
    }
    var data = fs.readFileSync(path.join(userDataPath, "data/projects.json"), 'utf8');
    projects = JSON.parse(data);
    var html = "";
    for (var i = 0; i < projects.length; i++) {
        var elem = projects[i];
        var name = "Jenkins Project";
        if (elem.projectName == "") {
            name = localFunc.getProjectNameByUrl(elem.url);
        }
        else {
            name = elem.projectName;
        }
        html += constrctProjectDiv(i, name);
    }
    if(projects.length) {
        $("#projects").html(html);
    }
    $(".list-item").addClass("blue");
    $(".list-item").attr("status_color", "blue");
    var width = 0;
    var height = parseInt($("#projects").css("height"));
    $("#projects").children().each(function (index, elem) {
        width = Math.max(width, parseInt($($(elem).children()[0]).css("width")));
    });
    var winSize = { width: (width + 30), height: (height + 20) };
    ipcRenderer.send("setWidth", JSON.stringify(winSize));
    if(!fs.existsSync(path.join(userDataPath, "data/config.json"))) {
        fs.writeFileSync(path.join(userDataPath, "data/config.json"),"[]");
    }

    // config.json
    data = fs.readFileSync(path.join(userDataPath, "data/config.json"), 'utf8');
    config = JSON.parse(data);
    if(config.hasOwnProperty("refresh_interval")) {
        refresh_interval= config.refresh_interval;
    }
    if(config.hasOwnProperty("remindStyle")) {
        var val = config.remindStyle;
        var redata = ipcRenderer.sendSync("setMsgStyle",val);
    }
}

// update
function update() {
    $("body").addClass("loading");
    setTimeout(function () {
        $("body").removeClass("loading");
    }, 1000);
    for (var i = 0; i < projects.length; i++) {
        getStatus(i);
    }
}

//judge become be worse
function getStatusValue(status) {
    switch (status) {
        case "blue":
            return 0;
        case "blue_anime":
            return 0;
        case "yellow_anime":
            return 1;
        case "yellow_anime":
            return 1;
        case "red_anime":
            return 2;
        case "red_anime":
            return 2;
        default:
            return 5;
    }
}
//get status
function removeOriStatus(id) {
    $("#" + id).removeClass("blue blue_anime red red_anime yellow yellow_anime disabled");
}
function getStatus(id) {
    var APIUrl = localFunc.construcUrlByNameAndToken(projects[id].userName, projects[id].token,
        projects[id].url + "/api/json?tree=color,lastBuild[timestamp]");
    request.setTimeout
    request.get(APIUrl, { timeout: (refresh_interval - 1) * 1000 }, function (err, httpResponse, body) {
        var result = {};
        try {
            result = JSON.parse(body);
        }
        catch (e) {
            result['color'] = "disabled";
        }
        var haveClass = "blue blue_anime red red_anime yellow yellow_anime disabled";
        if(haveClass.indexOf(result['color']) == -1) {
            result['color'] = "disabled";
        }
        if (getStatusValue(result['color']) > getStatusValue($("#" + id).attr("status_color"))) {
            ipcRenderer.send("system", "trayflickerStart");
        }
        removeOriStatus(id);
        $("#" + id).addClass(result['color']);
        $("#" + id).attr("status_color", result['color']);
    });
}

//some event
$(".list-item").click(function (e) {
    if (isMovingWindow) {
        return;
    }
    var id = $(this).attr("id");
    var url = projects[id].url;
    shell.openExternal(url);
});

// let window follow by mouse move
window.addEventListener("mousedown", function (e) {
    isMousePress = true;

    const { pageX, pageY } = e;
    mouseX = pageX;
    mouseY = pageY;
});
window.addEventListener("mouseup", function (e) {
    isMousePress = false;
    setTimeout(function () {
        isMovingWindow = false;
    }, 100);
});
window.addEventListener("mousemove", function (e) {
    if (isMousePress) {
        const { pageX, pageY } = e;
        var deltaX = pageX - mouseX;
        var deltaY = pageY - mouseY;
        var moveIgnorePX = 5;
        if (isMovingWindow == false && deltaX * deltaX + deltaY * deltaY < moveIgnorePX * moveIgnorePX) {
            return;
        }
        isMovingWindow = true;
        const win = require('electron').remote.getCurrentWindow();
        const pos = win.getPosition();
        pos[0] = pos[0] + pageX - mouseX;
        pos[1] = pos[1] + pageY - mouseY;
        win.setPosition(pos[0], pos[1], true);
    }
});